<template>
	<div class="app-container">
        <div class="custom-navbar">
            <div class="nav-left">
                <!-- <van-icon name="arrow-left" class="nav-icon" @click="backRoute" /> -->
            </div>
            <div class="nav-title">{{ this.navTitle }}</div>
            <div class="nav-right">
                <van-icon name="add-o" class="nav-icon" @click.stop="toggleActionPanel" ref="addIcon" />
            </div>
        </div>

		<!-- 搜索区域 -->
		<div class="search-section">
			<van-search
				v-model="searchKeyword"
				class="custom-search"
				placeholder="搜索"
				background="#ffffff"
				:round="true"
				:show-action="false"
				>
				<template #left-icon>
					<van-icon name="search" size="18" style="padding-left: 5px;padding-right: 5px;" />
				</template>
			</van-search>
		</div>

		<!-- 联系人列表 -->
		<div class="contact-list">
			<ContactItem
			v-for="contact in filteredContacts"
			:key="contact.id"
			:contact="contact"
			@click-preview = "previewImage"
			/>
		</div>

		<!-- 图片预览 -->
		<van-image-preview
			v-model="showImagePreview"
			:images="previewImages"/>

		<div class="action-panel" v-if="showActionPanel" :style="actionPanelStyle">
			<div class="action-item" @click.stop="createGroup">
				<van-icon name="friends-o" />
				<span>发起群聊</span>
			</div>
			<div class="action-divider"></div>
			<div class="action-item" @click="addFriend">
				<van-icon name="add-o" />
				<span>添加朋友</span>
			</div>
			<div class="action-divider"></div>
			<div class="action-item">
				<van-icon name="scan" />
				<span>扫一扫</span>
			</div>
		</div>
	</div>
</template>

<script>
	import ContactItem from './contactItem.vue'
	import { postAction, getFileAccessHttpUrl } from '@/api'
	import { formatTime }  from '@/util/util.js'
	import mqHandler from './util/mqHandler' // 引入mqHandler
	import Vue from 'vue'

	export default {
		name: "chat",
		components: {
			ContactItem,
		},

		data() {
			return {
				navTitle: "聊天",
				searchKeyword: "",
				contacts: [],
				userId: this.$store.getters.userid,
				showImagePreview: false,
				previewImages: [],
				showActionPanel: false,
				actionPanelStyle: {
					top: '50px',
					right: '10px'
				}
			}
		},
		computed: {
			// 过滤后的联系人列表
			filteredContacts() {
				if (!this.searchKeyword) return this.contacts;
				return this.contacts.filter(contact =>
					contact.displayName.toLowerCase().includes(this.searchKeyword.toLowerCase())
					|| contact.lastContent.includes(this.searchKeyword.toLowerCase())
				);
			}
		},
		created() {
			if(!this.$store.getters.mqClient){
				console.log("创建mq连接:")
				mqHandler.connect();
			}
			console.log("mqHandler",this.$store.getters.mqClient)
			// this.initContactsList();
			// 初始化MQ监听
			this.initMQListener();
			console.log("当前事件总线:",Vue.prototype.$bus)
		},
    watch: {
      '$route' () {
        this.initContactsList()
      }
    },
		beforeDestroy() {
			// 组件销毁时移除监听
			Vue.prototype.$bus.$off('message', this.handleNewMessage);
		},
    mounted() {
      this.initContactsList()
      // this.initMQListener();
    },
    methods: {
			// backRoute() {
			// 	this.$router.push({ name: 'main' })
			// 	console.log("断开mq连接:")
			// 	mqHandler.disconnect();
			// },
			toggleActionPanel() {
				this.showActionPanel = !this.showActionPanel;
				if (this.showActionPanel) {
					// 获取图标位置，动态设置弹框位置
					// const iconRect = this.$refs.addIcon.$el.getBoundingClientRect();
					// this.actionPanelStyle = {
					// 	top: `${iconRect.bottom + 5}px`,
					// 	right: `${window.innerWidth - iconRect.right}px`
					// };
				}
			},
			createGroup() {
				this.$router.push('/coordination/createGroup')
			},
      addFriend() {
        this.showActionPanel = false;
        this.$router.push({name: 'addfriend'})
      },
			initMQListener() {
				// 使用事件总线监听新消息
				console.log("监听新消息:",Vue.prototype.$bus.$on('message', this.handleNewMessage))
				console.log("当前事件总线:",Vue.prototype.$bus)
			},
			handleNewMessage(message) {
				if (message.type != 'OneToGroup'){
					// 判断是否是当前用户的消息
					if (message.receiveid !== this.userId) return;
				}

				// 获取联系人ID（群聊或私聊）
				const contactId =  message.sendid;
				console.log('contactId',contactId)

				// 查找是否已有该联系人
				const existingContactIndex = this.contacts.findIndex(c => c.goalId === contactId);
				console.log('存在联系人索引:', existingContactIndex);
				console.log('message:', message);
				if (existingContactIndex !== -1) {

					// 更新现有联系人
					const updatedContact = {...this.contacts[existingContactIndex]};


					if (message.type != 'OneToGroup'){
						updatedContact.lastContent = this.getLastContent(message);
					}else {
						updatedContact.lastContent = message.info.realname + ':' + this.getLastContent(message);
					}
					// 更新最后一条消息
					updatedContact.lastSendTime = formatTime(message.time);
					updatedContact.unread = updatedContact.unread + 1;

					// 从原位置移除
					this.contacts.splice(existingContactIndex, 1);
					// 添加到顶部
					this.contacts.unshift(updatedContact);
				} else {
					// 创建新联系人
					const newContact = {
						goalId: contactId,
						avatar: message.type == 'OneToGroup' ? getFileAccessHttpUrl(message.avatar) : getFileAccessHttpUrl(message.info.avatar),
						displayName: message.type == 'OneToGroup' ? message.groupname : message.info.realname,
						lastContent: this.getLastContent(message),
						lastSendTime: formatTime(message.time),
						unread: 1,
						is_group: message.type == 'OneToGroup' ? 1 : 0,
						contextType: message.info.infotype
					};
					console.log(newContact)
					// 添加到顶部
					this.contacts.unshift(newContact);
				}
			},

			getLastContent(message) {
				// 根据消息类型返回不同的预览内容
				switch (message.info.infotype) {
					case 'image':
						return '[图片]';
					case 'voice':
						return '[语音]';
					case 'file':
						return '[文件]';
					default:
						return message.msgcontent || message.info.msgcontent;
				}
			},


			initContactsList() {
				postAction('/sys/chat/relative', {
					type: "meeting",
					userId: this.$store.getters.userid
				}).then((res) => {
					if (res.success) {
						this.processContacts(res.result);
					} else {
						console.error('加载联系人失败:', res.message);
					}
				}).catch((err) => {
					console.error('加载联系人异常:', err);
				});
			},

			processContacts(list) {
				// 按 lastSendTime 降序排序
				list.sort((a, b) => {
					const dateA = new Date(a.lastSendTime);
					const dateB = new Date(b.lastSendTime);
					return dateB - dateA;
				});

				list.forEach((e) => {

          postAction("/sys/chat/bot/selectkey",{id:e.goalId}).then(res=>{
            if(res.result){
              e.avatar = '/static/mobile/img/common/robot_default.png';
            }else {
              e.avatar = e.avatar ? getFileAccessHttpUrl(e.avatar) : '/static/mobile/img/common/user_default.webp';
            }
          })
          // e.avatar = e.avatar ? getFileAccessHttpUrl(e.avatar) : '/static/mobile/img/common/user_default.webp';
					e.lastSendTime = formatTime(e.lastSendTime, "yyyy-MM-dd HH:mm");

					// 根据消息类型设置预览内容
					if (e.contextType === 'image') {
						e.lastContent = '[图片]';
					} else if (e.contextType === 'file') {
						e.lastContent = '[文件]';
					} else if (e.contextType === 'voice') {
						e.lastContent = '[语音]';
					}
				});

				this.contacts = list;
			},
			previewImage(imageUrl) {
				// var ip = ImagePreview
				// var mq = mqHandler
				// console.log("ImagePreview", ip)
				// console.log("mqHandler", mq)
				this.previewImages = [imageUrl]
				this.showImagePreview = true
			},
			// openChat(contact) {
			// 	// 重置未读数
			// 	contact.unread = 0;
			// 	// 跳转到聊天页面
			// 	this.$router.push({
			// 		name: 'chat-room',
			// 		params: {
			// 			contactId: contact.goalId
			// 		}
			// 	});
			// }
		}
	}
</script>

<style scoped>
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	body {
		background-color: #f5f7fa;
		font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
		color: #333;
	}

	.app-container {
		margin: 0 auto;
		background: white;
		height: 95vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	/* 搜索区域 */
	.search-section {
		padding: 15px 16px;
		background-color: #fff;

	}

	/* 联系人列表 */
	.contact-list {
		flex: 1;
		overflow-y: auto;
		padding: 0 16px;
		background-color: #fff;
	}

	.contact-item {
		display: flex;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
		align-items: center;
	}

	.contact-item:last-child {
		border-bottom: none;
	}

	/* 自定义导航栏 */
	.custom-navbar {
		position: relative;
		height: 46px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 16px;
		background-color: #fff;
		border-bottom: 1px solid #f0f0f0;
		z-index: 100;
	}

	.nav-left, .nav-right {
		display: flex;
		align-items: center;
		width: 60px;
	}

	.nav-right {
		justify-content: flex-end;
	}

	.nav-title {
		font-size: 16px;
		font-weight: bold;
		color: #26B1A1;
	}

	.nav-icon {
		font-size: 16px;
		color: #26B1A1;
		padding: 8px;
		border-radius: 50%;
		transition: background-color 0.2s;
	}

	.nav-icon:active {
		background-color: #f0f0f0;
	}

	/* 自定义弹出菜单 */
	.action-panel {
		background-color: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
		overflow: hidden;
		width: 160px;
		position: absolute;
		z-index: 2000;
		transform-origin: top right;
		animation: scaleIn 0.2s cubic-bezier(0.22, 0.61, 0.36, 1);
	}

	.action-item {
		padding: 16px 20px;
		font-size: 16px;
		color: #26B1A1;
		display: flex;
		align-items: center;
		transition: background-color 0.2s;
	}

	.action-item:active {
		background-color: #f9f9f9;
	}

	.action-item .van-icon {
		margin-right: 12px;
		font-size: 18px;
	}

	.action-divider {
		height: 1px;
		background-color: #f0f0f0;
	}

	/* 遮罩层 */
	.overlay-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: transparent;
		z-index: 1000;
	}

	/* 动画 */
	@keyframes scaleIn {
		0% {
			opacity: 0;
			transform: scale(0.8) translateY(-10px);
		}
		100% {
			opacity: 1;
			transform: scale(1) translateY(0);
		}
	}

	.fade-enter-active, .fade-leave-active {
		transition: opacity 0.2s;
	}

	.fade-enter, .fade-leave-to {
		opacity: 0;
	}
</style>
